import * as readline from 'readline';
import { WaterSourceAPI } from './api-client.js';
import { SearchProcessor } from './search-processor.js';
import { AnswerGenerator } from './answer-generator.js';

// 创建标准输入输出接口
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

// 初始化API客户端和处理器
let api: WaterSourceAPI;
let searchProcessor: SearchProcessor;
let answerGenerator: AnswerGenerator;
let debugMode: boolean = false; // 调试模式标志

/**
 * 初始化服务
 */
async function init() {
  return new Promise<void>((resolve) => {
    rl.question('请输入水源社区Cookie: ', (cookie) => {
      api = new WaterSourceAPI(cookie);
      searchProcessor = new SearchProcessor(api);
      
      rl.question('请输入阿里云通义千问API Key: ', (apiKey) => {
        rl.question('请输入通义千问模型名称(默认为qwen-plus): ', (modelName) => {
          const model = modelName.trim() || 'qwen-plus';
          answerGenerator = new AnswerGenerator(apiKey, model);
          
          console.log(`初始化完成，使用模型: ${model}`);
          console.log('可用命令: search <关键词>, answer <问题>, preview <问题>, update-cookie <新cookie>, debug [on|off], help, exit');
          resolve();
        });
      });
    });
  });
}

/**
 * 显示帮助信息
 */
function showHelp() {
  console.log('可用命令:');
  console.log('  search <关键词> - 搜索水源社区');
  console.log('  answer <问题> - 基于水源社区内容回答问题');
  console.log('  preview <问题> - 只显示搜索结果预览，不生成回答');
  console.log('  update-cookie <新cookie> - 更新水源社区Cookie');
  console.log('  debug [on|off] - 开启/关闭调试模式，显示更多信息');
  console.log('  help - 显示帮助信息');
  console.log('  exit - 退出程序');
}

/**
 * 处理用户输入的命令
 */
async function handleCommand(line: string) {
  const [command, ...args] = line.trim().split(' ');
  const query = args.join(' ');
  
  switch (command.toLowerCase()) {
    case 'search':
      if (!query) {
        console.log('请提供搜索关键词');
        return;
      }
      
      try {
        console.log(`正在搜索: ${query}`);
        const results = await searchProcessor.getRelevantContent(query);
        console.log(`找到 ${results.topics.length} 个相关主题:`);
        
        // 按相关性排序显示结果
        const sortedTopics = [...results.topics].sort((a, b) => b.relevance - a.relevance);
        
        sortedTopics.forEach((topic, index) => {
          console.log(`\n[${index + 1}] ${topic.title}`);
          console.log(`链接: ${topic.url}`);
          console.log(`发布者: ${topic.username} | 回复数: ${topic.posts_count}`);
          console.log(`相关度: ${topic.relevance}`);
          console.log(`预览内容:`);
          console.log(topic.preview_content);
        });
      } catch (error) {
        console.error('搜索失败:', error instanceof Error ? error.message : String(error));
      }
      break;
      
    case 'preview':
      if (!query) {
        console.log('请提供问题');
        return;
      }
      
      try {
        console.log(`为问题生成预览: ${query}`);
        console.log('获取相关内容...');
        const results = await searchProcessor.getRelevantContent(query);
        
        if (results.topics.length === 0) {
          console.log('没有找到相关内容。');
          return;
        }
        
        console.log(`找到 ${results.topics.length} 个相关主题，生成预览...`);
        
        // 显示详细预览（不调用AI生成回答）
        const sortedResults = [...results.topics].sort((a, b) => b.relevance - a.relevance);
        
        console.log('\n============ 搜索结果详细信息 ============');
        for (let i = 0; i < Math.min(sortedResults.length, 5); i++) {
          const topic = sortedResults[i];
          
          console.log(`【${i+1}】${topic.title} (回复数: ${topic.posts_count})`);
          console.log(`链接: ${topic.url}`);
          console.log(`作者: ${topic.username} | 相关度: ${topic.relevance}`);
          console.log(`发布时间: ${new Date(topic.created_at).toLocaleString()}`);
          
          console.log('\n关键内容:');
          console.log(topic.preview_content);
          
          if (debugMode) {
            console.log('\n完整内容片段 (前300字符):');
            console.log(topic.full_content.substring(0, 300) + '...');
          }
          
          console.log('\n---------------------------------\n');
        }
        console.log('============================================\n');
      } catch (error) {
        console.error('生成预览失败:', error instanceof Error ? error.message : String(error));
      }
      break;
      
    case 'answer':
      if (!query) {
        console.log('请提供问题');
        return;
      }
      
      try {
        console.log(`正在为问题寻找答案: ${query}`);
        console.log('1. 获取相关内容...');
        const results = await searchProcessor.getRelevantContent(query);
        
        if (results.topics.length === 0) {
          console.log('没有找到相关内容，无法回答问题');
          return;
        }
        
        console.log(`2. 找到 ${results.topics.length} 个相关主题，生成回答...`);
        
        // 在调试模式下，输出更多信息
        if (debugMode) {
          console.log('\n调试信息:');
          console.log(`获取到的主题数: ${results.topics.length}`);
          console.log(`各主题相关度: ${results.topics.map(t => t.relevance).join(', ')}`);
          console.log(`各主题回复数: ${results.topics.map(t => t.posts_count).join(', ')}`);
          console.log(`各主题标题: ${results.topics.map(t => t.title).join(' | ')}`);
        }
        
        const answer = await answerGenerator.generateAnswer(query, results.topics);
        
        console.log('\n回答:');
        console.log('='.repeat(50));
        console.log(answer);
        console.log('='.repeat(50));
      } catch (error) {
        console.error('回答问题失败:', error instanceof Error ? error.message : String(error));
      }
      break;
      
    case 'debug':
      if (args.length === 0 || args[0].toLowerCase() === 'on') {
        debugMode = true;
        console.log('调试模式已开启');
      } else if (args[0].toLowerCase() === 'off') {
        debugMode = false;
        console.log('调试模式已关闭');
      } else {
        console.log(`当前调试模式: ${debugMode ? '开启' : '关闭'}`);
      }
      break;
      
    case 'update-cookie':
      if (!query) {
        console.log('请提供新的Cookie');
        return;
      }
      
      api.setCookie(query);
      console.log('Cookie已更新');
      break;
      
    case 'help':
      showHelp();
      break;
      
    case 'exit':
      console.log('退出程序');
      rl.close();
      process.exit(0);
      break;
      
    default:
      console.log(`未知命令: ${command}`);
      showHelp();
      break;
  }
}

// 主程序入口
(async function main() {
  console.log('水源社区AI助手启动中...');
  await init();
  
  rl.on('line', async (line) => {
    try {
      await handleCommand(line);
    } catch (error) {
      console.error('命令处理出错:', error instanceof Error ? error.message : String(error));
    }
    rl.prompt();
  });
  
  rl.on('close', () => {
    console.log('程序已退出');
    process.exit(0);
  });
  
  rl.prompt();
})(); 